var express = require('express');
var router = express.Router();
var db = require('../config/mysql');
var vertoken = require('../config/token');

function filterMenu(data, menuIds) {
  let parents = data.filter(item => item.parentId == 0);
  let childs = data.filter(item => item.parentId != 0);
  childs.forEach(c => {
    c.checked = menuIds.includes(c.id)
    parents.forEach(p => {
      c.parentId == p.id && (p.children ? p.children.push(c) : p.children = [c]);
      if(!p.hasOwnProperty("children") || !p.children.length) p.checked = menuIds.includes(p.id)
    })
  });
  return parents
}

// 获取角色列表
router.post('/getRoleList',(req, res) => {
  let { roleName, pageNo, pageSize } = req.body;
  // let sql = `SELECT COUNT(id) AS total FROM role WHERE roleName LIKE ?`;
  // let sql2 = `SELECT * FROM role WHERE roleName LIKE ? limit ?,?`;
  // let totalSql = await db.query(sql, [`%${roleName || '%'}%`]);
  // let reslute = await db.query(sql2, [`%${roleName || '%'}%`, (pageNo - 1) * pageSize, pageSize]);
  // res.json({
  //   status: 200,
  //   message: '成功',
  //   data: {
  //     total: totalSql[0].total,
  //     reslute
  //   },
  //   timestamp: db.getTime()
  // })

  let sql = `SELECT * FROM role WHERE 1 = 1`;
  if(roleName) {
    sql += ` AND roleName LIKE '%${roleName || '%'}%'`
  }
  sql += ` limit ${(pageNo - 1) * pageSize},${pageSize};SELECT FOUND_ROWS() as total FROM role WHERE roleName LIKE '%${roleName || '%'}%';`;
  let reslute = db.query(sql, []);
  console.log(reslute)
  res.json({
    status: 200,
    message: '成功',
    data: reslute[0],
    ...reslute[1][0],
    timestamp: db.getTime()
  })
})

// 新增角色
router.post('/addRole', (req, res) => {
  let { roleName } = req.body;
  let sql = `SELECT * FROM role WHERE roleName = ?`;
  db.query(sql, [roleName], (reslute) => {
    if(!reslute.length) {
      let sql = `INSERT INTO role (roleName) VALUES (?)`;
      db.query(sql, [roleName], (reslute) => {
        res.json({
          status: 200,
          message: '成功',
          data: reslute,
          timestamp: db.getTime()
        })
      })
    } else res.json({
      status: 300,
      message: '角色名重复',
      data: null,
      timestamp: db.getTime()
    })
  })
})

// 更新用户
router.post('/editRole', (req, res) => {
  let { roleName, id } = req.body;
  let sql = `SELECT * FROM role WHERE roleName = ? AND id != ?`;
  db.query(sql, [roleName, id], (reslute) => {
    if(!reslute.length) {
      let sql = `UPDATE role SET roleName = ? WHERE id = ?`;
      db.query(sql, [roleName, id], (reslute) => {
        res.json({
          status: 200,
          message: '成功',
          data: reslute,
          timestamp: db.getTime()
        })
      })
    } else res.json({
      status: 300,
      message: '角色名重复',
      data: null,
      timestamp: db.getTime()
    })
  })
})

// 删除角色  (判断有无用户使用该角色，同时删除角色对应的菜单与按钮)
router.post('/delRole', (req, res) => {
  let { roleId } = req.body;
  let sql = `SELECT * FROM user WHERE userRole = ?`;
  db.query(sql, [roleId], async (data) => {
    if(!data.length) {
      let sql1 = `DELETE FROM role WHERE id = ?`;
      let sql2 = `DELETE FROM rolebtn WHERE roleId = ?`;
      let sql3 = `DELETE FROM rolemenu WHERE roleId = ?`;
      let res1 = await db.query(sql1, [roleId])
      let res2 = await db.query(sql2, [roleId, res1])
      db.query(sql3, [roleId, res2], (reslute) => {
        res.json({
          status: 200,
          message: '成功',
          data: null,
          timestamp: db.getTime()
        })
      })
    } else res.json({
      status: 300,
      message: '当前角色已被使用，无法删除',
      data: null,
      timestamp: db.getTime()
    })
  })
})

// 获取角色菜单
router.post('/getRoleMenu', (req, res) => {
  let { roleId } = req.body;
  let sql = `SELECT * FROM rolemenu WHERE roleId = ? AND disable != 0`;
  db.query(sql, [roleId], (reslute) => {
    let menuIds = reslute.reduce((total, item) => {
      total.push(item.menuId);
      return total;
    }, [])
    let sql2 = `SELECT * FROM menu`;
    db.query(sql2, [], (reslute) => {
      let data = filterMenu(reslute, menuIds);
      res.json({
        status: 200,
        message: '成功',
        data,
        timestamp: db.getTime()
      })
    })
  })
})

// 更新角色权限
router.post('/updateRoleMenu', (req, res) => {
  let { roleId, roleList } = req.body;
  let sql = `SELECT * FROM rolemenu WHERE roleId = ?`;
  db.query(sql, [roleId], (data) => {
    let allMenu = data.map(i => i.menuId)
    let newMenu = roleList.filter(i => !allMenu.includes(i))
    newMenu.length && newMenu.forEach(menuId => {
      let sql = `INSERT INTO rolemenu (roleId, menuId, disable) VALUES (?, ?, 1)`;
      db.query(sql, [roleId, menuId])
    })
    data.forEach(item => {
      let sql2 = `UPDATE rolemenu SET disable = ? WHERE id = ?`;
      db.query(sql2, [roleList.includes(item.menuId) ? 1 : 0, item.id])
    })
  })
})

// 角色 菜单 按钮 类型(add、edit、delt)
// 根据菜单获取角色按钮权限
router.post('/getRoleButtons', (req, res) => {
  let { roleId, menuId } = req.body;
  let sql = `SELECT buttonKey FROM rolebtn WHERE roleId = ? AND menuId = ? AND disable != 0`
  db.query(sql, [roleId, menuId], (roleBtn) => {
    let sql2 = `SELECT * FROM btnauth WHERE menuId = ?`
    db.query(sql2, [menuId], (menuBtn) => {
      let keyArr = roleBtn.map(i => i.buttonKey);
      res.json({
        status: 200,
        message: '成功',
        data: menuBtn.reduce((total, item) => {
          item.checked = keyArr.includes(item.buttonKey);
          total.push(item);
          return total
        }, []),
        timestamp: db.getTime()
      })
    })
  })
})

// 修改角色按钮权限
router.post('/updateRoleButton', (req, res) => {
  let { roleId, menuId, buttonKey, checked } = req.body;
  let sql = `SELECT * FROM rolebtn WHERE roleId = ? AND menuId = ? AND buttonKey = ?`
  db.query(sql, [roleId, menuId, buttonKey], (reslute) => {
    if(reslute.length) {
      let sql = `UPDATE rolebtn SET disable = ? WHERE id = ?`;
      db.query(sql, [checked, reslute[0].id], (reslute) => {
        res.json({
          status: 200,
          message: '成功',
          data: reslute,
          timestamp: db.getTime()
        })
      })
    } else {
      let sql = `INSERT INTO rolebtn (roleId, buttonKey, menuId, disable) VALUES (?, ?, ?, ?)`;
      db.query(sql, [roleId, buttonKey, menuId, checked], (reslute) => {
        res.json({
          status: 200,
          message: '成功',
          data: reslute,
          timestamp: db.getTime()
        })
      })
    }
  })
})

module.exports = router;